import time
import logging
from flask import Blueprint, jsonify, session
from flask_jwt_extended import create_access_token, verify_jwt_in_request
from src.db_models.base import db
from src.db_models.models import User, TermCollection, Term
from src.process_db import get_terms_list, generate_term_results
from src.process_text import change_format, extract_terms_from_text, get_text_and_model
from src.prompts import build_prompt
from src.llm_apis.select_api import select_api
from flask import request, redirect, url_for, flash
from flask_jwt_extended import jwt_required, get_jwt_identity
from src.upload_file import allowed_file, handle_file_upload  # 导入处理文件上传的函数

# 设置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

api = Blueprint('api', __name__)


@api.route('/access_profile', methods=['GET'])
@jwt_required()  # 使用 JWT 验证
def personal_homepage():
    user_id = get_jwt_identity()  # 获取当前用户的身份
    user = User.query.get(user_id)  # 根据 user_id 从数据库查询用户
    if user:
        return jsonify(user.to_dict())  # 返回 JSON 格式的用户信息
    else:
        return {"msg": "User not found"}, 401


@api.route('/token', methods=['POST'])
def create_token():
    email = request.form.get("email", None)
    password = request.form.get("password", None)

    user = User.query.filter_by(email=email).first()

    if user is None or user.password != password:
        return jsonify({"msg": "Bad email or password"}), 401

    access_token = create_access_token(identity=user.id)
    return jsonify(access_token=access_token)


@api.route('/verify_token', methods=['POST'])
@jwt_required()
def verify_token():
    try:
        verify_jwt_in_request()
        return jsonify({"valid": True}), 200
    except:
        return jsonify({"valid": False}), 401


@api.route('/register', methods=['POST'])
def register():
    user_data = {
        'nickname': request.form.get('nickname'),
        'email': request.form.get('email'),
        'verification': request.form.get('verification'),
        'password': request.form.get('password')
    }

    if (user_data['email'] in session and
            session[user_data['email']]['otp'] == user_data['verification'] and
            time.time() - session[user_data['email']]['time'] < 5 * 60):
        # 验证成功后，检查邮箱是否已注册
        if User.query.filter_by(email=user_data['email']).first():
            flash("该邮箱已注册", "danger")
            return redirect(url_for('page.register'))  # 如果已经注册，返回注册页面

        # 创建新用户
        new_user = User(
            nickname=user_data['nickname'],
            email=user_data['email'],
            password=user_data['password']  # 这里可以选择哈希密码
        )
        db.session.add(new_user)
        db.session.commit()
        # 注册成功，提示用户并重定向到登录页面
        flash("注册成功！请登录。", "success")
        return redirect(url_for('page.login_page'))  # 重定向到登录页面
    else:
        flash("验证码无效或已过期，请重新获取。", "danger")
        return redirect(url_for('page.register'))  # 验证失败，重新显示注册页面


@api.route('/upload_term_collection', methods=['POST'])
@jwt_required()
def upload_term_collection():
    user_id = get_jwt_identity()

    if 'file' not in request.files:
        return jsonify({"error": "没有文件部分"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "没有选择文件"}), 400

    if file and allowed_file(file.filename):
        table_name = request.form.get('table_name')
        category = request.form.get('category')

        try:
            handle_file_upload(file, table_name, category, user_id)
            return jsonify({"message": "术语集上传成功"}), 200
        except Exception as e:
            logger.error(f"上传术语集时发生错误: {str(e)}")
            return jsonify({"error": str(e)}), 500
    else:
        return jsonify({"error": "不允许的文件类型"}), 400


@api.route('/get_user_term_collections', methods=['GET'])
@jwt_required()
def get_user_term_collections():
    user_id = get_jwt_identity()

    try:
        term_collections = TermCollection.query.filter_by(user_id=user_id).all()
        return jsonify([collection.to_dict() for collection in term_collections]), 200
    except Exception as e:
        logger.error(f"获取用户术语集时发生错误: {str(e)}")
        return jsonify({"error": f"获取失败: {str(e)}"}), 500


@api.route('/delete_term_collection/<int:collection_id>', methods=['DELETE'])
@jwt_required()
def delete_term_collection(collection_id):
    user_id = get_jwt_identity()

    term_collection = TermCollection.query.get(collection_id)

    if not term_collection:
        return jsonify({"error": "术语集不存在"}), 404

    if term_collection.user_id != user_id:
        return jsonify({"error": "没有权限删除此术语集"}), 403

    try:
        # 删除与此术语集相关的所有术语
        Term.query.filter_by(term_collection_id=collection_id).delete()

        # 删除术语集
        db.session.delete(term_collection)
        db.session.commit()

        return jsonify({"message": "术语集已成功删除"}), 200
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除术语集时发生错误: {str(e)}")
        return jsonify({"error": f"删除失败: {str(e)}"}), 500


@api.route("/extract-terms", methods=["POST"])
def extract_terms():
    text_input, model_choice = get_text_and_model()
    gen_prompt = build_prompt(text_input)

    output = select_api(model_choice, gen_prompt)
    if output is None:
        return jsonify({"error": "Invalid model choice"}), 400

    numbered_result = change_format(output)
    return jsonify(numbered_result)


@api.route("/search_terms", methods=["POST"])
def search_terms_from_db():
    text_input, model_choice = get_text_and_model()
    terms_list = get_terms_list()

    # 从输入文本中使用模糊匹配提取多个术语
    cn_terms = extract_terms_from_text(text_input, terms_list)
    if not cn_terms:
        return jsonify({"error": "未找到任何术语"}), 400

    results = generate_term_results(cn_terms, model_choice)
    return jsonify(results)
